<?php

namespace app\admin\controller;

use app\BaseController;
use app\model\archives_model\UserArchiveModel;
use app\model\DepartmentLevelModel;
use app\model\DepartmentModel;
use app\model\LoginLogModel;
use app\model\UserModel;
use think\App;

class UserStatistics extends BaseController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    /**
     * 用户统计
     * @return bool|string
     */
    public function NumberPeople(): bool|string
    {
        try {
            $UserModel = new UserModel();
            $LoginLogModel = new LoginLogModel();
            $data['total'] = $UserModel->where('unit_id', '=', $this->userData['unit_id'])->count();
            $data['admin'] = $UserModel->where([
                ['unit_id', '=', $this->userData['unit_id']],
                ['role_mode', '<', 2]
            ])->count();
            $data['boy'] = $UserModel->where([
                ['unit_id', '=', $this->userData['unit_id']],
                ['sex', '=', 1]
            ])->count();
            $data['girl'] = $UserModel->where([
                ['unit_id', '=', $this->userData['unit_id']],
                ['sex', '=', 2]
            ])->count();
            $LoginLog = $LoginLogModel->where([
                ['unit_id', '=', $this->userData['unit_id']],
                ['time', '>', strtotime(date("Y-m-d"))]
            ])->column('uid');
            $LoginLog = array_unique($LoginLog);
            $data['online'] = count($LoginLog);
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 用户在线活跃度
     * @return bool|string
     */
    public function online(): bool|string
    {
        try {
            $date = custom_time();
            $data = [];
            $LoginLogModel = new LoginLogModel();
            $UserModel = new UserModel();
            foreach ($date as $item) {
                $data['date'][] = date('d',strtotime($item['value']));
                $uids = $LoginLogModel->where([
                    ['unit_id', '=', $this->userData['unit_id']],
                    ['time', 'between', [strtotime($item['start_time']), strtotime($item['end_time'])]]
                ])->distinct(true)->column('uid');
                $total = count($uids);
                $boy = $UserModel->where([
                    ['id','in',$uids],
                    ['sex','=',1]
                ])->count();
                $data['boy'][] = $boy;
                $data['girl'][] = $total - $boy;
            }
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 其他数据统计
     * @return bool|string
     */
    public function other(): bool|string
    {
        try {
            $DepartmentModel = new DepartmentModel();
            $DepartmentCount = $DepartmentModel->where('unit_id', '=', $this->userData['unit_id'])->order('id','desc')->count();
            $UserModel = new UserModel();
            $ConsultCount = $UserModel->where([
                ['unit_id', '=', $this->userData['unit_id']],
                ['role_mode', '=', 2]
            ])->count();
            $AppealCount = $UserModel->where([
                ['unit_id', '=', $this->userData['unit_id']],
                ['status', '=', 3]
            ])->count();
            $UserArchiveModel = new UserArchiveModel();
            $data = $UserArchiveModel->where([
                ['unit_id','=', $this->userData['unit_id']],
                ['type_id', '=', 7],
                ['is_repeal', '=', 0]
            ])->field('id,content')->select()->toArray();
            $status = 0;
            $status2 = 0;
            $status3 = 0;
            foreach ($data as $item) {
                if (!empty($item['content'])){
                    $content = json_decode($item['content'], true);
                    foreach ($content as $v) {
                        if ($v['quesitionId']??0 == 155) {
                            switch ($v['answerId']) {
                                case 242:
                                    $status++;//正常
                                    break;
                                case 243:
                                    $status2++;//异常
                                    break;
                                case 244:
                                    $status3++;//好
                                    break;
                            }
                        }
                    }
                }
            }
            return success([
                'DepartmentCount' => $DepartmentCount,
                'ConsultCount' => $ConsultCount,
                'AppealCount' => $AppealCount,
                'status' => $status,
                'status2' => $status2,
                'status3' => $status3,
            ]);
        } catch (\Exception $e) {
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 残疾类型数据统计
     * @return bool|string
     */
    public function disability(): bool|string
    {
        try {
            $type = [
                1 => [
                    'name' => '视力残疾',
                    'num' => 0
                ],
                2 => [
                    'name' => '听力残疾',
                    'num' => 0
                ],
                3 => [
                    'name' => '言语残疾',
                    'num' => 0
                ],
                4 => [
                    'name' => '肢体残疾',
                    'num' => 0
                ],
                5 => [
                    'name' => '智力残疾',
                    'num' => 0
                ],
                6 => [
                    'name' => '精神残疾',
                    'num' => 0
                ],
                7 => [
                    'name' => '多重残疾',
                    'num' => 0
                ],
            ];
            $data2 = [
                'total' => 0
            ];
            $UserArchiveModel = new UserArchiveModel();
            $data = $UserArchiveModel->where([
                ['unit_id','=', $this->userData['unit_id']],
                ['type_id', '=', 4],
                ['is_repeal', '=', 0]
            ])->field('id,content')->select()->toArray();
            foreach ($data as $item) {
                $content = json_decode($item['content'], true);
                if (!empty($content['answerIds'])){
                    $data2['total']++;
                    foreach ($content['answerIds'] as $v) {
                        if (empty($v[0])) continue;
                        if (!isset($type[$v[0]]['num'])) continue;
                        $type[$v[0]]['num']++;
                    }
                }
            }
            foreach ($type as $v) {
                $data2['name'][] = $v['name'];
                $data2['num'][] = $v['num'];
            }
            return success($data2);
        } catch (\Exception $e) {
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 用户年龄段细分
     * @return bool|string
     */
    public function age(): bool|string
    {
        try {
            $UserModel = new UserModel();

            // 核心优化：用SQL直接统计各年龄段、性别的数量，避免PHP循环
            $stats = $UserModel->field([
                // 用CASE将年龄分组为1-6（对应原来的6个年龄段）
                'CASE 
                WHEN age BETWEEN 0 AND 5 THEN 1
                WHEN age BETWEEN 6 AND 10 THEN 2
                WHEN age BETWEEN 11 AND 15 THEN 3
                WHEN age BETWEEN 16 AND 20 THEN 4
                WHEN age BETWEEN 21 AND 25 THEN 5
                WHEN age > 25 THEN 6
             END AS age_group',
                'sex', // 性别（1=男，其他=女）
                'COUNT(id) AS count' // 统计该分组数量
            ])
                ->where([
                    ['unit_id', '=', $this->userData['unit_id']],
                    ['role_mode', '=', 3]
                ])
                ->group('age_group, sex') // 按年龄段和性别分组
                ->select()
                ->toArray();

            // 初始化统计结果（与原结构一致）
            $data2 = [
                'boy' => 0, 'girl' => 0,
                'boy2' => 0, 'girl2' => 0,
                'boy3' => 0, 'girl3' => 0,
                'boy4' => 0, 'girl4' => 0,
                'boy5' => 0, 'girl5' => 0,
                'boy6' => 0, 'girl6' => 0,
            ];

            // 映射数据库统计结果到$data2（仅循环统计结果，最多12条）
            foreach ($stats as $item) {
                $ageGroup = $item['age_group'];
                $sex = $item['sex'];
                $count = $item['count'];

                // 生成键名（如age_group=1且sex=1对应'boy'）
                $key = ($sex == 1 ? 'boy' : 'girl') . ($ageGroup > 1 ? $ageGroup : '');
                if (isset($data2[$key])) {
                    $data2[$key] = $count;
                }
            }

            return success($data2);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }


    /**
     * 用户入学年段分布
     * @return bool|string
     */
    public function LearningStage(): bool|string
    {
        try {
            $DepartmentLevelModel = new DepartmentLevelModel();
            $DepartmentModel = new DepartmentModel();
            $UserModel = new UserModel();
            $data = $DepartmentLevelModel->where([
                ['unit_id', '=', $this->userData['unit_id']],
                ['status','=',1]
            ])->field('id,name')->select()->toArray();
            foreach ($data as &$item) {
                $DepartmentIds = $DepartmentModel->where('mode','=',$item['id'])->column('id');
                $item['num'] = $UserModel->where('department_id','in',$DepartmentIds)->count('id');
            }
            $date = custom_time([],'y');
            $data2 = [];
            foreach ($date as $key => $value) {
                if ($key == 1) continue;
                $start_time = strtotime($value['start_time']);
                $end_time = strtotime($value['end_time']);
                $data2['date'][] = $value['value'];
                $data2['num'][] = $UserModel->where([
                    ['unit_id', '=', $this->userData['unit_id']],
                    ['role_mode','=',3],
                    ['time','between',[$start_time,$end_time]]
                ])->count('id');
            }
            return success([
                'data2' => $data2,
                'data' => $data,
            ]);
        } catch (\Exception $e) {
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 部门
     * @return bool|string
     */
    public function department(): bool|string
    {
        try {
            $data = [
                [
                    'name' => '一级部门',
                    'num' => 0,
                    'level' => 1
                ],[
                    'name' => '二级部门',
                    'num' => 0,
                    'level' => 2
                ],[
                    'name' => '三级部门',
                    'num' => 0,
                    'level' => 3
                ],[
                    'name' => '四级部门',
                    'num' => 0,
                    'level' => 4
                ],[
                    'name' => '五级部门',
                    'num' => 0,
                    'level' => 5
                ],[
                    'name' => '六级部门',
                    'num' => 0,
                    'level' => 6
                ],[
                    'name' => '七级部门',
                    'num' => 0,
                    'level' => 7
                ],[
                    'name' => '八级部门',
                    'num' => 0,
                    'level' => 8
                ],[
                    'name' => '九级部门',
                    'num' => 0,
                    'level' => 9
                ],[
                    'name' => '十级部门',
                    'num' => 0,
                    'level' => 10
                ],
            ];
            $DepartmentModel = new DepartmentModel();
            $UserModel = new UserModel();
            foreach ($data as &$item) {
                $department_id = $DepartmentModel->where([
                    ['unit_id','=',$this->userData['unit_id']],
                    ['level','=',$item['level']]
                ])->column('id');
                $item['num'] = $UserModel->where('department_id','in',$department_id)->count('id');
            }
            $date = custom_time([],'y');
            $data2 = [];
            foreach ($date as $key => $value) {
                if ($key == 1) continue;
                $start_time = strtotime($value['start_time']);
                $end_time = strtotime($value['end_time']);
                $data2['date'][] = $value['value'];
                $data2['num'][] = $UserModel->where([
                    ['unit_id', '=', $this->userData['unit_id']],
                    ['role_mode', '=', 3],
                    ['time','between',[$start_time,$end_time]]
                ])->count('id');
            }
            return success([
                'data2' => $data2,
                'data' => $data,
                'count' => $UserModel->where([
                    ['unit_id', '=', $this->userData['unit_id']],
                    ['role_mode', '=', 3]
                ])->count('id'),
            ]);
        } catch (\Exception $e) {
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

}